﻿using INTEX.DataBase;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core.Events;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Data;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for ProductionOrder.xaml
    /// </summary>
    public partial class JLTSMPCOWS : DocumentBase
    {
        #region-------------Properties-----------------------
        string rownid = "";
        bool IsLoaded = false;
        DataRow CurrentRow = null;
        DataSet SResult = null;
        DataRow LastRow = null;
        DataSet SetMap = null; 
        public DataSet dsResult;
        JLTSMPCOWSData m_Data, m_DataX;
        public DataSet dsParamaters;
        JLTSMPCOWSReport m_rpt;
        DataTable tbUser = null;
        public SETINTEXDB SetData
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetData");
            }
        }
        public SETINTEXDB SetProd
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetProd");
            }
        }
        CollectionViewSource vwVKP
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwVKP");
            }
        }
        DataRow dwVKP
        {
            get
            {
                if (vwVKP.View == null)
                    return null;
                if ((DataRowView)vwVKP.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwVKP.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwTVKP
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwTVKP");
            }
        }
        DataRow dwTVKP
        {
            get
            {
                if (vwTVKP.View == null)
                    return null;
                if ((DataRowView)vwTVKP.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwTVKP.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwWARP
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwWARP");
            }
        }
        DataRow dwWARP
        {
            get
            {
                if (vwWARP.View == null)
                    return null;
                if ((DataRowView)vwWARP.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwWARP.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwWEFT
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwWEFT");
            }
        }
        DataRow dwWEFT
        {
            get
            {
                if (vwWEFT.View == null)
                    return null;
                if ((DataRowView)vwWEFT.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwWEFT.View.CurrentItem).Row;
            }
        }
        string ART
        {
            get
            {
                return m_Data.Left(txtART.Text.ToString() + "                      ", 20);
            }
        }
        bool IsSamp
        {
            get
            {
                if (ChkS.IsChecked == true)
                    return true;
                else
                {
                    return false;
                }
            }
        }
        BindingListCollectionView cvVKPRICE
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(dlgVKPRICE.ItemsSource);
            }
        }

        string user = "";
        #endregion
        public JLTSMPCOWS()
        {
            InitializeComponent();
            m_Data = new JLTSMPCOWSData();
            this.Name = "生产成本";
            if (IsSamp)
            {
                txtART.Text = "S";
            }
            else
            {
                txtART.Text = "J";
            }
        } 
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (IsLoaded)
                    return;
                IsLoaded = true;
                vwVKP.View.CurrentChanged += vwVKP_CurrentChanged;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return;

        }
        void vwVKP_CurrentChanged(object sender, EventArgs e)
        {
            if (dwVKP == null)
                return;
      
            SResult = m_Data.BuildData(dwVKP, true);
            SetProd.Clear();
            SetProd.Merge(SResult);
            ResetScreen();
        }       
        private void btnPrint_Click(object sender, EventArgs e)
        {  
            m_rpt = new JLTSMPCOWSReport();
            DataRow dwVKP; DataRow dwVK;
            dwVKP = SetProd.Tables["ICC_VKPRICE"].Rows[0];
            dwVK = SetProd.Tables["VKPOS"].Rows[0];
            if (dwVK["VKPVG"].ToString().Trim() == "USD")
            {
                if (dwVKP["VKKLIEFBED"].ToString().Trim() == "")
                {
                    MessageBox.Show("请输入贸易方式！");
                    return;
                }
                else
                {
                    if (dwVKP["VKKLIEFBED"].ToString().Trim() == "CIF" || dwVKP["VKKLIEFBED"].ToString().Trim() == "CNF")
                    {
                        if (dwVKP["MPRICESHIP"].ToString().Trim() == "0")
                        {
                            MessageBox.Show("请填写海运费！");
                            return;
                        }
                    }
                }
            }
          
            m_rpt.dsSource = SetProd;
            m_rpt.WriteExcelReport("OpenExcel");
        }
        private void btnFilter_Click(object sender, RoutedEventArgs e)
        {
            string filter = "VKPART LIKE '" + ART + "%'";
            cvVKPRICE.CustomFilter = filter;

        }
        private void btnFilterClear_Click(object sender, RoutedEventArgs e)
        {
            cvVKPRICE.CustomFilter = null;
        }
        private void cmdRefresh_Click(object sender, RoutedEventArgs e)
        {
            DataRow dwData = SetData.ICC_VKPRICE.NewRow();
            dwData["MANDANT"] = "00";
            DataSet SResult = m_Data.Refresh(dwData);
            SetData.Clear();
            SetData.Merge(SResult);
        }
        private void cmdLoad_Click(object sender, RoutedEventArgs e)
        {
            if (IsSamp)
            {
                if (!ART.StartsWith("S"))
                    return;
            }
            DataRow dwData = SetData.ICC_VKPRICE.NewRow();
            dwData["MANDANT"] = "00";
            dwData["VKPART"] = ART;
            DataSet SResult = m_Data.LoadVKPRICE(dwData);
            SetData.Clear();
            SetData.Merge(SResult);
        }
        private void Calcute(DataRow row)
        {
            double price1 = 0, value1 = 0, price2 = 0, value2 = 0, price3 = 0, value3 = 0, price = 0, value = 0;
            double usage = 0;
            price1 = Convert.ToDouble(row["MPRICEM"].ToString());
            usage = Convert.ToDouble(row["MUSAGE"].ToString());
            value1 = price1 * usage * 0.01;
            price2 = Convert.ToDouble(row["MPRICED"].ToString());
            value2 = price2 * usage * 0.01;

            price = price1 + price2 + price3;
            value = value1 + value2 + value3;
            row["MVALUEM"] = Helpers.Helper.RoundX(value1, 100);
            row["MVALUED"] = Helpers.Helper.RoundX(value2, 100);
            row["MCOST"] = Helpers.Helper.RoundX(Convert.ToDouble(row["MVALUEM"].ToString()) + Convert.ToDouble(row["MVALUED"].ToString()), 100);
        }
        private void ResetScreen()
        {

            string filter = "";
            DataRow[] rows = null;
            DataTable tb = null;
            string tbname = "";
            double price1 = 0, value1 = 0, price2 = 0, value2 = 0, price3 = 0, value3 = 0, price = 0, value = 0;
            double usage = 0;
            double valuemw = 0;
            double valuemf = 0;
            double valuedw = 0, valuedf = 0, costmy = 0, costdy = 0;
            double valuey = 0, valueb = 0, valued = 0, valuee = 0;
            try
            {
                if (vwTVKP.View != null)
                {
                    vwTVKP.View.MoveCurrentToFirst();
                }
                if (dwTVKP == null)
                    return;
                double rate = 0;
                double vkqty = 0;
                string currency = dwTVKP["CURRENCY"].ToString();
                string PREH = dwTVKP["PREH"].ToString();
                vkqty = Convert.ToDouble(dwTVKP["VKPQTY"].ToString());
                if (dwTVKP["VKPUNIT"].ToString().Trim().Contains("M"))
                {
                    vkqty = vkqty / 0.9144;
                }
                if (vkqty < 3000) rate = 0.1;
                if (vkqty < 2000) rate = 0.2;
                if (vkqty < 1000) rate = 0.5;
                if (vkqty < 500) rate = 1;
                rate = 0;
                txtRatio.Text = (1 + rate).ToString();
                double exchange = Convert.ToDouble(dwTVKP["USD2RMB"].ToString());
                exchange = exchange * 1.17;
                if (exchange == 0)
                    exchange = 6.2 * 1.17;
                double weftdensity = Convert.ToDouble(dwTVKP["MVKWEFTDEN"].ToString());

                if (weftdensity == 0)
                    weftdensity = 1;
                #region=======warp=======
                foreach (DataRow row in SetProd.ICC_VKPWARP.Rows)
                {
                    Calcute(row);
                    valuemw += Convert.ToDouble(row["MVALUEM"].ToString());
                    valuedw += Convert.ToDouble(row["MVALUED"].ToString());
                }
                costmy += valuemw;
                costdy += valuedw;
                dwTVKP["MCOSTMW"] = valuemw;
                dwTVKP["MCOSTDW"] = valuedw;
                #endregion
                #region=======weft=======
                value1 = 0;
                value2 = 0;
                value3 = 0;
                foreach (DataRow row in SetProd.ICC_VKPWEFT.Rows)
                {
                    Calcute(row);
                    valuemf += Convert.ToDouble(row["MVALUEM"].ToString());
                    valuedf += Convert.ToDouble(row["MVALUED"].ToString());
                }
                costmy += valuemf;
                costdy += valuedf;
                dwTVKP["MCOSTMF"] = Helpers.Helper.RoundX(valuemf, 100);
                dwTVKP["MCOSTDF"] = Helpers.Helper.RoundX(valuedf, 100);
                dwTVKP["MCOSTMY"] = Helpers.Helper.RoundX(costmy * (1 + rate), 100);
                dwTVKP["MCOSTDY"] = Helpers.Helper.RoundX(costdy * (1 + rate), 100);
                #endregion
                double priceagent = Convert.ToDouble(dwTVKP["MPRICEAGENT"].ToString());
                double priceship = Convert.ToDouble(dwTVKP["MPRICESHIP"].ToString());
                if (!PREH.Contains("M"))
                {
                    priceagent = priceagent / 0.9144;
                    priceship = priceship / 0.9144;
                }
                dwTVKP["MCOSTAGENT"] = Helpers.Helper.RoundX(priceagent * 0.01 * exchange, 100);
                dwTVKP["MCOSTSHIP"] = Helpers.Helper.RoundX(priceship * 0.01 * exchange, 100);
                dwTVKP["MCOSTFLIGHT"] = dwTVKP["MPRICEFLIGHT"];

                dwTVKP["MCOSTPROD"] = Convert.ToDouble(dwTVKP["MCOSTFIN"].ToString())
                    + Convert.ToDouble(dwTVKP["MCOSTPAK"].ToString())
                     + Convert.ToDouble(dwTVKP["MCOSTFVV"].ToString())
                      + Convert.ToDouble(dwTVKP["MCOSTFADD"].ToString());

                dwTVKP["MVKCOST"] = Convert.ToDouble(dwTVKP["MCOSTMY"].ToString())
                   + Convert.ToDouble(dwTVKP["MCOSTDY"].ToString())
                    + Convert.ToDouble(dwTVKP["MCOSTPROD"].ToString());


                double cost = Convert.ToDouble(dwTVKP["MVKCOST"].ToString())
                    + Convert.ToDouble(dwTVKP["MCOSTAGENT"].ToString())
                    + Convert.ToDouble(dwTVKP["MCOSTSHIP"].ToString())
                + Convert.ToDouble(dwTVKP["MCOSTFLIGHT"].ToString())
                    + Convert.ToDouble(dwTVKP["MCOSTADD"].ToString());

                double cprice = Convert.ToDouble(dwTVKP["MCPRICE"].ToString());

                if (currency.Contains("USD"))
                    cprice = cprice * exchange;
                if (!PREH.Contains("M"))
                    cprice = cprice / 0.9144;
                dwTVKP["MCOSTGROSS"] = Helpers.Helper.RoundX(cprice - cost, 100);
                dwTVKP["MCOSTNET"] = Helpers.Helper.RoundX((cprice - cost) / 1.17, 100);
                dwTVKP["MCOSTNETW"] = Helpers.Helper.RoundX(10000 * Convert.ToDouble(dwTVKP["MCOSTNET"].ToString()) / weftdensity,100);

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void cmdVKPEDIT_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwVKP == null)
                {
                    MessageBox.Show("请先选择一条记录!");
                    return;
                }
                DataRow dwNew = SetProd.ICC_VKPRICE.NewRow();
                dwNew.ItemArray = dwVKP.ItemArray;

                if (dwNew["CONTROL"].ToString().Trim() == "NO")
                {
                    dwNew["CONTROL"] = "ON";
                }
                SetProd.ICC_VKPRICE.Rows.Add(dwNew);
                SResult = m_Data.BuildData(dwNew, true);
                SetProd.Clear();
                SetProd.Merge(SResult);
                if (vwTVKP.View != null)
                    vwTVKP.View.MoveCurrentToFirst();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                ResetScreen();
                detail.Focus();
            }
        }
        private void cmdReset_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwTVKP == null)
                {
                    MessageBox.Show("请先选择一条记录!");
                    return;
                }
                SResult = m_Data.Reset(dwTVKP);
                SetProd.Clear();
                SetProd.Merge(SResult);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                ResetScreen();
            }
        }
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ResetScreen();
                foreach (DataRow row in SetProd.ICC_VKPWARP.Rows)
                {
                    if (row["CONTROL"].ToString() == "DN")
                        continue;
                    m_Data.INTEXDBC.SaveICC_VKPWARP(row);
                }
                foreach (DataRow row in SetProd.ICC_VKPWEFT.Rows)
                {
                    if (row["CONTROL"].ToString() == "DN")
                        continue;
                    m_Data.INTEXDBC.SaveICC_VKPWEFT(row);
                }
                foreach (DataRow row in SetProd.ICC_VKPRICE.Rows)
                {
                    m_Data.INTEXDBC.SaveICC_VKPRICE(row);
                }
                SResult = m_Data.BuildData(dwTVKP, false);
                SetProd.Clear();
                SetProd.Merge(SResult);
                if (vwTVKP.View != null)
                {
                    vwTVKP.View.MoveCurrentToFirst();
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnInsertWarp_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwWARP == null)
                {
                    MessageBox.Show("请先选择一条记录!");
                    return;
                }
                DataRow dwNew = SetProd.ICC_VKPWARP.NewRow();
                dwNew.ItemArray = dwWARP.ItemArray;
                dwNew["ROWNID"] = "0";
                dwNew["NEWTIME"] = m_Data.date;
                dwNew["NEWUSER"] = m_Data.UserID;
                var query = (from DataRow row in SetProd.ICC_VKPWARP.AsEnumerable()
                             select row["MPOS"].ToString())
                       .Max();
                double mpos = Convert.ToDouble(query.ToString()) + 10;
                dwNew["MPOS"] = Helpers.Helper.Right("0000" + mpos, 4);
                SetProd.ICC_VKPWARP.Rows.Add(dwNew);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            } 
        }
        private void btnInsertWeft_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwWEFT == null)
                {
                    MessageBox.Show("请先选择一条记录!");
                    return;
                }
                DataRow dwNew = SetProd.ICC_VKPWEFT.NewRow();
                dwNew.ItemArray = dwWEFT.ItemArray;
                dwNew["ROWNID"] = "0";
                dwNew["NEWTIME"] = m_Data.date;
                dwNew["NEWUSER"] = m_Data.UserID;
                var query = (from DataRow row in SetProd.ICC_VKPWEFT.AsEnumerable()
                             select row["MPOS"].ToString())
                       .Max();
                double mpos = Convert.ToDouble(query.ToString()) + 10;
                dwNew["MPOS"] = Helpers.Helper.Right("0000" + mpos, 4);
                SetProd.ICC_VKPWEFT.Rows.Add(dwNew);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnDeleteWarp_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwWARP == null)
                {
                    MessageBox.Show("请先选择一条记录!");
                    return;
                }
                m_Data.INTEXDBC.DeleteICC_VKPWARP(dwWARP, 1);
                dwWARP["CONTROL"] = "DN";
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            } 
        }
        private void btnDeleteWeft_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwWEFT == null)
                {
                    MessageBox.Show("请先选择一条记录!");
                    return;
                }
                m_Data.INTEXDBC.DeleteICC_VKPWEFT(dwWEFT, 1);
                dwWEFT["CONTROL"] = "DN";
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        } 
    }
}
